package com.ruoyi.common.sms.utils;

/**
 * @author fxy
 * @date 2024/9/12
 * @Description
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.ruoyi.common.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Random;


public class SMSUtil {

    //替换成自己申请的accessKeyId
    private static String accessKeyId = "LTAI5tNcuwJCH4z8BaLKSWNR";
    //替换成自己申请的accessKeySecret
    private static String accessKeySecret = "2Sp5cu5E6BTHGAGNx3MpG2VVQxJ4uj";
    static final String product = "Dysmsapi";
    static final String domain = "dysmsapi.aliyuncs.com";
    // 生成四位验证码
    public static String generateFourDigitCode() {
        Random random = new Random();
        int code = 1000 + random.nextInt(9000); // 生成1000到9999之间的随机数
        return String.valueOf(code);
    }
    // 发送短信的方法
    public static void sendSms(String phoneNumbers, String signName, String templateCode, String param) {
        try {
            System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
            System.setProperty("sun.net.client.defaultReadTimeout", "10000");
            // 初始化acsClient, 暂不支持region化
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            SendSmsRequest request = new SendSmsRequest();
            request.setPhoneNumbers(phoneNumbers);
            request.setSignName(signName);
            request.setTemplateCode(templateCode);
            request.setTemplateParam(param);
            request.setOutId("yourOutId");
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            if (!"OK".equals(sendSmsResponse.getCode())) {
                throw new RuntimeException(sendSmsResponse.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("发送短信失败");
        }
    }


    // 生成并发送验证码(商家端）
//    public static void sendVerificationCodeByShop(String phone) {
//        System.out.println("phone = " + phone);
//        String code = generateFourDigitCode(); // 生成验证码
//        System.out.println("code = " + code);
//        String messageBody = JSON.toJSONString(code); // 将验证码转为JSON格式
//        System.out.println("messageBody = " + messageBody);
//        sendSms(phone, "车辆综合服务商家端", "SMS_154950909", messageBody); // 发送验证码
//    }
    // 生成并发送验证码（商家端）
    public static void sendVerificationCodeByShop(String phone) {
        System.out.println("phone = " + phone);
        String code = generateFourDigitCode(); // 生成验证码

        System.out.println("code = " + code);

        // 创建包含验证码的JSON对象
        JSONObject json = new JSONObject();
        json.put("code", code); // "code" 是模板中占位符的名称
        String messageBody = json.toJSONString(); // 将JSON对象转为字符串

        System.out.println("messageBody = " + messageBody);
        sendSms(phone, "阿里云短信测试", "SMS_154950909", messageBody); // 发送验证码
    }
//    public static void main(String[] args) {
//        // 测试发送验证码
//        sendVerificationCodeByShop("17630656963");
//    }
public static void setPhoneAndCode(String phone,String code) {
    System.out.println("11111 = " + phone+"  code = "+ code);
    redisService.setCacheObject(phone, code);
    try {
        Thread.sleep(5000); // 延迟 1 秒
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("redisService.getCacheObject(phone) = " + redisService.getCacheObject(phone));
}
    // 生成并发送验证码(用户端）
    //@Autowired
    @Autowired
    private static RedisTemplate<String, Object> redisTemplate;
    static RedisService redisService = new RedisService();
    public static void sendVerificationCodeByUser(String phone) {
        System.out.println("传入的phone = " + phone);
        String code = generateFourDigitCode(); // 生成验证码
        System.out.println("生成的验证码 = " + code);
        //setPhoneAndCode(phone,code);
        redisTemplate.opsForValue().set(phone, code);
        //redisService.setCacheObject(phone, code);
        System.out.println("22222");
        try {
            Thread.sleep(5000); // 延迟 1 秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //用户验证码存入Redis，设置3分钟过期时间
        //redisService.setCacheObject(phone, code);
        redisTemplate.opsForValue().get(phone);
        System.out.println("redisTemplate = " + redisTemplate.opsForValue().get(phone));
        //redisService.getCacheObject(phone);
        //redisService.setCacheObject(phone, code,5L,TimeUnit.MINUTES);
        //redisService.setValueWithExpiration(phone, code, 3, TimeUnit.MINUTES);
        String messageBody = JSON.toJSONString(code); // 将验证码转为JSON格式
        //sendSms(phone, "阿里云短信测试", "SMS_154950909", messageBody); // 发送验证码
    }

}
